<?php
namespace  app\admin\model;

use think\Model;

class Category extends Model{
    /**
     * 获取分类树，指定分类则返回指定分类极其子分类，不指定则返回所有分类树
     * @param  integer $id    分类ID
     * @param  boolean $field 查询字段
     * @return array          分类树
     */
    public function getTree($id = 0, $field = true){
        /* 获取当前分类信息 */
        $Tree = new \tree\Tree;
        $Tree::$treeList = [];
        $list = Category::field($field)->order('id asc')->select();
//        return $list;
        return $Tree->tree($list,0,0);
    }

    public function info($id){
        $map['id'] = $id;
        $info=Category::where($map)->find();
        return $info;
    }


    /**
     * 检测分类是否存在
     *
     * @param string $name
     * @param int $pid
     * @param int $id
     * @return bool
     */
    public function name_exists($name, $pid, $id=0) {
        $where = "name='" . $name . "' AND pid='" . $pid . "' AND id<>'" . $id . "'";
        $result = Category::where($where)->count('id');
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 生成spid
     *
     * @param int $pid 父级ID
     */
    public function get_spid($pid) {
        if (!$pid) {
            return 0;
        }
        $pspid = Category::where(array('id'=>$pid))->value('spid');
//        $pspid =$pspid['spid'];
//        echo $this->getLastSql();
//        echo $pspid;
//        print_r($pspid);
        if ($pspid) {
            $spid = $pspid . $pid . '|';
        } else {
            $spid = $pid . '|';
        }
        return $spid;
    }

    /**
     * 获取分类下面的所有子分类的ID集合
     *
     * @param int $id
     * @param bool $with_self
     * @return array $array
     */
    public function get_child_ids($id, $with_self=false) {
        $spid = Category::where(array('id'=>$id))->value('spid');
        $spid = $spid ? $spid .= $id .'|' : $id .'|';
        $id_arr = Category::field('id')->where(array('spid'=>array('like', $spid.'%')))->select();
        $array = array();
        foreach ($id_arr as $val) {
            $array[] = $val['id'];
        }
        $with_self && $array[] = $id;
        return $array;
    }

}